/*******************************************************************************
 * Copyright 2013 Mindaugas Idzelis
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package incontrol.bf3.state;

import incontrol.bf3.protocol.events.datatype.Squad;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.base.Objects;

public class PlayerList {

	private ImmutableList<PlayerState> players;

	public PlayerList() {
		this(Collections.<PlayerState> emptySet());
	}

	public PlayerList(Collection<PlayerState> players) {
		this.players = ImmutableList.copyOf(players);
	}

	public Map<String, PlayerState> byName() {
		return Maps.uniqueIndex(getPlayers(),
				new Function<PlayerState, String>() {
					public String apply(PlayerState player) {
						return player.name;
					}
				});
	}

	public Collection<PlayerState> getPlayers() {
		return players;
	}

	public Multimap<Integer, PlayerState> getTeams() {
		return Multimaps.index(getPlayers(),
				new Function<PlayerState, Integer>() {
					public Integer apply(PlayerState player) {
						return player.teamId;
					}
				});
	}

	public Multimap<Squad, PlayerState> getSquads() {
		return Multimaps.index(getPlayers(),
				new Function<PlayerState, Squad>() {
					public Squad apply(PlayerState player) {
						return new Squad(player.teamId, player.squadId);
					}
				});
	}

	@Override
	public String toString() {
		return Objects.toStringHelper(this).add("players", players).toString();
	}

	@Override
	public int hashCode() {
		return Objects.hashCode(players);
	}

	@Override
	public boolean equals(Object object) {
		if (object instanceof PlayerList) {
			PlayerList that = (PlayerList) object;
			return Objects.equal(this.players, that.players);
		}
		return false;
	}

}
